package com.partsoft.spring.webapp;

import java.io.FileNotFoundException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.util.Assert;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.util.SystemPropertyUtils;
import org.springframework.web.util.Log4jWebConfigurer;
import org.springframework.web.util.WebUtils;

public class Log4jConfigListener extends org.springframework.web.util.Log4jConfigListener implements
		ServletContextListener {

	@Override
	public void contextInitialized(ServletContextEvent event) {
		ServletContext servletContext = event.getServletContext();
		String location = servletContext.getInitParameter(Log4jWebConfigurer.CONFIG_LOCATION_PARAM);
		String intervalStr = servletContext.getInitParameter(Log4jWebConfigurer.REFRESH_INTERVAL_PARAM);
		try {
			if (location != null) {
				try {
					if (!ResourceUtils.isUrl(location)) {
						location = SystemPropertyUtils.resolvePlaceholders(location);
						location = WebUtils.getRealPath(servletContext, location);
					}
				} catch (FileNotFoundException ex) {
					throw new IllegalArgumentException(ex.getMessage());
				}
			}
			Assert.hasText(location);
			Assert.hasText(intervalStr);
			if (StringUtils.hasText(intervalStr)) {
				try {
					Long.parseLong(intervalStr);
				} catch (Exception e) {
					throw new IllegalArgumentException();
				}
				long interval = Long.parseLong(intervalStr);
				Assert.isTrue(interval <= 30000);
			}
			super.contextInitialized(event);
			System.setProperty("dits.log4j.config.location", location);
			System.setProperty("dits.log4j.config.interval", intervalStr);
		} catch (Throwable e) {
			throw new IllegalArgumentException(e);
		}

	}

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		super.contextDestroyed(event);
	}

}
